/**
 * 
 */
package fr.ece.ing4.chatapplication.client;

import org.jgroups.Address;
import org.jgroups.Message;
import org.jgroups.View;

import fr.ece.ing4.chatapplication.api.ChatMessage;
import fr.ece.ing4.chatapplication.api.TransportDriver;
import fr.ece.ing4.chatapplication.api.TransportReceiver;

/**
 * @author enzo
 *
 */
public class ChatRoomController implements TransportReceiver{
    private int chatRoomNumber;
	private String chatRoomName;
	private TransportDriver driver;
	private Address serverAddress;

    private ClientFrame clientFrame;
	
	public ChatRoomController(String clusterName,String name,Address sa, ClientFrame clientFrame, int chatRoomNumber)
	{
		this.clientFrame = clientFrame;
        this.chatRoomNumber = chatRoomNumber;
        chatRoomName = clusterName;
		driver = new TransportDriver(chatRoomName,name,this);
		serverAddress = sa;

	}

	@Override
	public void printView(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void receiveChatMessage(Message msg) {
		// TODO Auto-generated method stub
		
		//get the message and print it to the view
		ChatMessage m = (ChatMessage) msg.getObject();
		if(m.getClusterName().equals(chatRoomName) && m.getType()==ChatMessage.CHAT && m.getType()==ChatMessage.RECV)
		{
            clientFrame.writeMessage(m.getData(), chatRoomNumber );
			//pass m.getData() to the view (using Observable ?)
		}
	}

	/**
	 * @return the chatRoomName
	 */
	public String getChatRoomName() {
		return chatRoomName;
	}

	public void disconnect()
	{
		driver.disconnect();
	}
	//à appeler lorsque l'on clique sur "send" et que cette chatroom est selectionée
	public void sendTextMessage(String message)
	{
		ChatMessage m = new ChatMessage(driver.getAddress(), serverAddress, chatRoomName, ChatMessage.CHAT, ChatMessage.SEND, message);
		driver.sendMessage(m);
	}
	@Override
	public void onViewChanged(View v) {
		// TODO Auto-generated method stub
		
	}

}
